package com.example.service.impl;

import com.example.domain.UserDetail;
import com.example.domain.dto.SysUserDto;
import com.example.domain.pojo.SysPermission;
import com.example.domain.pojo.SysRole;
import com.example.mapper.IPermissionMapper;
import com.example.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljs
 * @date 2025/7/22
 */
@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private IPermissionMapper permissionMapper;

    @Autowired
    private IUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //登录查询
        SysUserDto sysUserDto = userMapper.selectByUsername(username);
        UserDetail userDetail = new UserDetail();

        if (sysUserDto == null) {
            throw new UsernameNotFoundException(username);
        }else {
            //查询权限
            List<SysRole> roles = sysUserDto.getRoles();
            List<Integer> roleIds = null;
            if (roles != null) {
                roleIds = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
            }
            List<SysPermission> permissions = permissionMapper.selectPersByRoleIds(roleIds);
            List<String> collect = permissions.stream().map(SysPermission::getCode).collect(Collectors.toList());

            System.out.println("打印权限列表："+collect);
            sysUserDto.setPermissions(collect);
            //存如detail中
            userDetail.setSysUser(sysUserDto);
            userDetail.setUserId(sysUserDto.getUserId());
        }
        return userDetail;
    }
}
